package com.shujia.flink.sql
import org.apache.flink.streaming.api.scala._
import org.apache.flink.table.api._
import org.apache.flink.table.api.bridge.scala._
import org.apache.flink.types.Row

object Demo5Canal {
  def main(args: Array[String]): Unit = {

    val bsEnv: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    val bsSettings: EnvironmentSettings = EnvironmentSettings
      .newInstance()
      .useBlinkPlanner() //指定计划器为blink
      .inStreamingMode() //指定流模式
      .build()
    /**
      *
      * 构建flink table环境
      *
      */
    val bsTableEnv: StreamTableEnvironment = StreamTableEnvironment.create(bsEnv, bsSettings)


    bsTableEnv.executeSql(
      """
        |
        |CREATE TABLE stu (
        |  id STRING,
        |  name STRING,
        |  age BIGINT,
        |  gender STRING,
        |  clazz STRING
        |) WITH (
        | 'connector' = 'kafka',
        | 'topic' = 'student.stu',
        | 'properties.bootstrap.servers' = 'master:9092,node1:9092,node2:9092',
        | 'properties.group.id' = 'asdsa',
        | 'format' = 'canal-json',  -- 使用 canal-json 格式
        | 'canal-json.ignore-parse-errors' = 'true'
        |)
        |
      """.stripMargin)

    bsTableEnv.executeSql(
      """
        |
        |CREATE TABLE avg_age (
        |  clazz STRING,
        |  avgAge DOUBLE,
        |  PRIMARY KEY (clazz) NOT ENFORCED
        |) WITH (
        |  'connector' = 'jdbc',
        |  'url' = 'jdbc:mysql://master:3306/student?useUnicode=true&characterEncoding=UTF-8',
        |  'table-name' = 'avg_age',
        |  'username' = 'root',
        |  'password' = '123456'
        |)
        |
      """.stripMargin)



    /**
      * 实时统计每隔班级的平均年龄
      *
      */


    bsTableEnv.executeSql(
      """
        |
        |insert into avg_age
        |select clazz,avg(cast(age as double)) as avgAge from
        |stu
        |group by clazz
        |
        |
      """.stripMargin)





  }
}
